package com.domain.service.impl;

import com.domain.common.Result;
import com.domain.dao.SmsCodeMapper;
import com.domain.pojo.SmsCode;
import com.domain.service.SmsCodeService;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional(rollbackFor = Exception.class)
public class SmsCodeServiceImpl implements SmsCodeService {
    @Autowired
    private SmsCodeMapper smsCodeMapper;

    /**
     * 获取验证码  保存验证码和手机号
     *
     * @param phone
     * @param code
     * @return
     */
    @Override
    public Result saveSmsCode(String phone, String code) {
        //如果存在手机号就更新验证码
        SmsCode smsCodeselect = smsCodeMapper.seleByPhone(phone);
        if (NotNullUtils.isNotNullObject(smsCodeselect)) {
            smsCodeselect.setCode(code);
            smsCodeselect.setCreatTime(new Date());
            smsCodeMapper.updateByPrimaryKeySelective(smsCodeselect);
        } else {
            SmsCode smsCode = new SmsCode();
            smsCode.setCode(code);
            smsCode.setId(UUIDUtils.getRandomUUID());
            smsCode.setPhone(phone);
            smsCode.setCreatTime(new Date());
            smsCodeMapper.insertSelective(smsCode);
        }
        return Result.success("保存成功");
    }

    /**
     * 验证手机号得时效
     *
     * @param smsCode
     * @param phoneNumber
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public SmsCode checkSmsCodeTime(String phoneNumber, String smsCode) {
        SmsCode sc = smsCodeMapper.checkSmsCodeTime(phoneNumber, smsCode);
        return sc;
    }

    @Override
    public void delect(String id) {
        smsCodeMapper.deleteByPrimaryKey(id);
    }
}
